// pages/main/me/authentication_un/authentication.js
import { getLessLimitSizeImage } from '../resume_editor/index.js';
import { uploadFile } from  '../resume_editor/uploadAliyun/index';
import { bankList } from '../bank_card/banks.js'; 
Page({
  /**
   * 页面的初始数据
   */
  data: {
    applydisabled: true,
    idcardInfo:{
      name: '',
      idCardNumber: ''
    },
    imgList: {
      'front': '',
      'back': '',
    },
    bank: {
      bankName: '',
      bankCode: '',
      bankCardNumber: ''
    },
    imgBase:{
      'front': '',
      'back': '',
    },

    verified: '',
    windowWidth: 0, // 屏幕宽度
    scrollHeight: 0, // 滚动屏高度
    imageSize: 100, // 图片控制最大kb数
    idCardValidDate: '',    //身份证有效期

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let opt = {};
    if(options.param){
      opt = JSON.parse(options.param);
    }
    this.setData({
      verified: opt.verified,
      windowWidth: wx.getSystemInfoSync().windowWidth,
      scrollHeight: wx.getSystemInfoSync().windowHeight,
    })
    if(opt.verified){
      this.getUserIdCard()
    }
  },

  getUserIdCard: function (){
    let that = this
    getApp().$http.getUserIdCard().then(res=>{
      let idInfo = that.data.idcardInfo;
      idInfo.name = res.realName
      idInfo.idCardNumber = res.idCardNo
      idInfo.expireTime = res.expireTime
      let bankA = that.data.bank
      // bankA.bankName = res.bankName
      bankA.bankCardNumber = res.bankCardNo
      let imageSide = that.data.imgList
      imageSide.front = res.idCardImgA
      imageSide.back = res.idCardImgB
      that.setData({
        applydisabled: false,
        idcardInfo: idInfo,
        bank: bankA,
        imgList: imageSide,
      })
    })
  },

  // 上传身份证
  chooseIdCard(e){
    if(!this.data.applydisabled){
      return
    }
    let dataset = e.currentTarget.dataset; 
    if(!this.data.applydisabled){
      return
    }
    let that = this
    wx.chooseImage({
      count: 1,  
      sizeType: ['compressed'], 
      sourceType: ['album', 'camera'],  
      success: (res) => {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片  
        let imgPath = res.tempFilePaths[0];
        getLessLimitSizeImage('pressCanvas', imgPath, that.imageSize, that.windowWidth, (path) => {
          wx.showLoading({ title: '上传中，请稍等~' });
          let param = {
            "filePath":path,
            "name":"idCardFile",
          }
          getApp().$http.uploadImage(param,function complated(res){
            if (res.statusCode == 200) { 
              var result = JSON.parse(res.data);
              console.log(result)
              if (result.code == 10000) {
                if(!result.data.cards.length){
                  wx.showToast({
                    icon: 'none',
                    title: '请上传正确的身份证照片',
                    duration: 2000
                  });
                  return
                }
                that.data.imgList[result.data.cards[0].side] = path
                that.setData({
                  imgList: that.data.imgList
                })
                if(result.data.cards[0].side == 'front'){
                  that.setData({
                    idcardInfo: result.data.cards[0]
                  })
                }else{
                  that.setData({
                    idCardValidDate: result.data.cards[0].validDate
                  })
                }


                // 图片base64转换
                wx.getFileSystemManager().readFile({
                  filePath: path, 
                  encoding: 'base64', 
                  success: res => { 
                    that.data.imgBase[result.data.cards[0].side] = res.data
                  },fail(){
                    wx.showToast({
                      icon: 'none',
                      title: '上传图片失败',
                      duration: 2000
                    });
                  }
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: res.message,
                  duration: 2000
                });
              }
            } else {
              wx.showToast({
                icon: 'none',
                title: res,
                duration: 2000
              });
            }
          })                
        })
      }
    });
  },
  /**
   * 改变银行卡号
   */
  bindblur(e) {
    let dataset = e.currentTarget.dataset;
    let value = e.detail.value;
    this.getBankName(value);
  },

  // 获取银行卡开户行
  getBankName(bankCardNumber){
    let that = this;
    wx.request({
      url: `https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?cardNo=${bankCardNumber}&cardBinCheck=true`,
      success:(res) => {

        if(res.data.bank){
          let bankA = that.data.bank
          bankA.bankCode = res.data.bank
          bankA.bankName = bankList[res.data.bank]
          bankA.bankCardNumber = bankCardNumber
          that.setData({
            bank: bankA,
          })
        }else{
          wx.showToast({
            icon: "none",
            title: '输入的卡号我查询到开户行，请重新输入',
            duration: 2000
          })
        }


      }
    })
  },

  // 提交审核
  submitReview(e){
    wx.showLoading({ title: '提交中，请稍等~' });
    let idCardImgBName = this.data.imgList.back
    let idCardImgAName = this.data.imgList.front
    let validDate = this.data.idCardValidDate
    let data = {
      bankName: this.data.bank.bankName,
      bankCode: this.data.bank.bankCode,
      bankCardNumber: this.data.bank.bankCardNumber,
      idCardImgB: this.data.imgBase.back,
      idCardImgA: this.data.imgBase.front,
      
      idCardImgBName: idCardImgBName.slice(idCardImgBName.lastIndexOf('.')),
      idCardImgAName: idCardImgAName.slice(idCardImgAName.lastIndexOf('.')),
      identityNumber: this.data.idcardInfo.idCardNumber,
      name: this.data.idcardInfo.name,
      validDate: validDate.split('-')[1].replace(/\./g, '-'),
    }
    getApp().$http.submitReview(data).then(res=>{
      wx.hideLoading()
      wx.showToast({
        icon: 'none',
        title: '提交审核成功'
      });
      setTimeout(()=>{
        getApp().$routes.goTo(getApp().$routes.authentication_result);
      },1500)
    })
  },

  // 身份证编辑
  inputedit(e){
    let dataset = e.currentTarget.dataset;
    let name = dataset.name;
    let value = e.detail.value;
    console.log(name)
    console.log(value)
    let idcardInfoA = this.data.idcardInfo;
    idcardInfoA[name] = value,
    this.setData({
      idcardInfo: idcardInfoA
    })
    console.log(this.data.idcardInfo)

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})